package org.viva.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.StringWriter;

import org.springframework.util.FileCopyUtils;
import org.viva.core.Log;
import org.viva.core.exception.ActionException;

public class LogFileUtil {

	public static void full(String file, OutputStream os) throws Exception {
		FileInputStream fis = new FileInputStream(file);
		FileCopyUtils.copy(fis, os);
		fis.close();
	}

	public static String full(String file) throws Exception {
		FileReader fr = new FileReader(file);
		StringWriter sw = new StringWriter();
		FileCopyUtils.copy(fr, sw);
		String re = sw.toString();
		fr.close();
		sw.close();
		return re;
	}

	public static class SeekRead {
		public String	file;
		public long		startPoint;
		public long		endPoint;
		public String	text;
	}

	public synchronized static void seekHtml(SeekRead seek) throws ActionException {
		RandomAccessFile raf = null;
		try {
			File file2 = new File((String) (System.getProperty("catalina.base") == null ? "" : System.getProperty("catalina.base")) + seek.file);
			if (!file2.exists()) throw new ActionException("日志文件不存在!!!" + file2.getPath());
			raf = new RandomAccessFile(file2, "r");
			if (seek.startPoint == -1) {
				seek.startPoint = raf.length();
				raf.seek(raf.length());
			} else {
				raf.seek(seek.startPoint);
			}
			StringBuffer sb = new StringBuffer();
			String temp = null;
			while ((temp = raf.readLine()) != null) {
				sb.append(new String(temp.getBytes("iso8859-1"), "UTF-8") + "\n");
			}
			seek.text = sb.toString();
			seek.endPoint = raf.getFilePointer();
		} catch (Exception e) {
			throw new ActionException("查看日志文件错误", e);
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (Exception e) {
					Log.error(e.getMessage(), e);
				}
			}
		}
	}

}
